package com.elasticsearch.util;

import java.util.List;

import com.elasticsearch.config.ElasticsearchUtil;
import com.elasticsearch.dbuitl.DBCOperation;
import com.elasticsearch.pojo.FeedFavorite;

/**
 * 功能：读取数据库数据创建索引文件 作者：kangjie 时间：2011-9-28下午01:30:01
 */
public class CreatIndexMysql {

	/** 每次提交多少条数据记录 **/
	public static int PAGE_SIZE = 1000;
	 /**是否同步完成**/
    private static boolean finished = false ;
 
    private static int PAGE_NUMBER = 1;
    /**总记录数**/
    private static int COUNT = 0;
    /**总页数**/
    private static int PAGE_TOTAL = 0;
    
	public static void main(String[] args) {
		 ChildThread thread = new ChildThread();
		 thread.start();
	}

	public static class ChildThread extends Thread {
		@Override
		public void run() {
			while(true){
				if(finished)break;
			    try {
					addField();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		/**
		 * 功能：从数据库读取数据批量创建索引 作者：kangjie 时间：2011-9-28下午01:49:51
		 * @throws Exception 
		 */
		@SuppressWarnings({ "unchecked" })
		public void addField() throws Exception {
			/** 生成索引开始时间 **/
			long startTime = System.currentTimeMillis();
			/** 数据库工具类 **/
			DBCOperation db = new DBCOperation();
			
			if(COUNT == 0 ){
				/** 数据库总记录数 **/
				COUNT = db.totalRecord("SELECT COUNT(1) FROM an_feed_favorite");
				
				PAGE_TOTAL = COUNT % PAGE_SIZE == 0 ? COUNT / PAGE_SIZE : COUNT /PAGE_SIZE + 1;
        		if (PAGE_TOTAL < 1) {
        			PAGE_TOTAL = 1;
        		}
			}
			
			 if (PAGE_NUMBER <= PAGE_TOTAL) {
               //** 查询所有记录 **//
 				StringBuffer sql = new StringBuffer(
 						"SELECT feed_id,TITLE,LINK,DESCRIPTION,str_to_date(CREATE_TIME,'%Y-%m-%d %H:%i:%s') AS create_time FROM an_feed_favorite LIMIT ");
 				 sql.append((PAGE_NUMBER -1) *PAGE_SIZE+ ","+ PAGE_SIZE);
 				System.out.println("执行sql:" + sql.toString());
 				List<FeedFavorite> list = db.dbExecuteQuely(sql.toString());
 				//** 创建索引 **//*
 				exeCreateIndex(list, "medcl", "news");
 				PAGE_NUMBER ++;
            }else{
            	finished = true;
            } 
	
			/** 生成索引结束时间 **/
			long endTime = System.currentTimeMillis();
			System.out.println("生成索引时间:" + (endTime - startTime) / 1000 + "秒");
		}

		
		/***
		 * 功能：索引生成公共方法 作者：kangjie 时间：2011-9-30下午02:12:55
		 * @throws Exception 
		 */
		public void exeCreateIndex(List<FeedFavorite> list, String indexName,
				String typeName) throws Exception {
			/** 判断集合是否为空 **/
			if (list != null && list.size() > 0) {
				/** 集合对象用于批量加入文件数据生成索引文件 **/
				ElasticsearchUtil.createIndex(list, indexName, typeName);
				try {
					// 防止出现：远程主机强迫关闭了一个现有的连接
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
